package com.hhkj.admin.order.service.extend.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hhkj.admin.order.common.cont.OrderConst;
import com.hhkj.admin.order.common.cont.OrderItemConst;
import com.hhkj.admin.order.common.cont.OrderRefundConst;
import com.hhkj.admin.order.domain.Order;
import com.hhkj.admin.order.domain.OrderItem;
import com.hhkj.admin.order.model.dopo.OrderDo;
import com.hhkj.admin.order.model.dopo.OrderPo;
import com.hhkj.admin.order.service.base.OrderItemService;
import com.hhkj.admin.order.service.base.OrderService;
import com.hhkj.admin.order.service.extend.OrderExtendService;
import com.ruoyi.common.base.biz.service.extend.BaseExtendServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderExtendServiceImpl
        extends BaseExtendServiceImpl<Order, OrderDo, OrderPo, OrderService>
        implements OrderExtendService {

    @Autowired
    private OrderItemService itemService;

    @Override
    public Order getByNum(String num) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getNum, num);
        return this.getService().getOne(queryWrapper, false);
    }

    @Override
    public boolean cancel(Long id) {
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getId, id)
                .set(Order::getStatusCode, OrderConst.StatusEnum.CANCEL.getCode());
        return this.getService().update(updateWrapper);
    }

    @Override
    public boolean applyRefund(Long id, List<Long> itemList) {
        LambdaUpdateWrapper<Order> orderUpdateWrapper = new LambdaUpdateWrapper<>();
        orderUpdateWrapper.eq(Order::getId, id)
                .set(Order::getRefundStatusCode, OrderRefundConst.StatusEnum.REFUNDING.getCode());
        boolean result = this.getService().update(orderUpdateWrapper);
        if (!result) {
            return false;
        }
        LambdaUpdateWrapper<OrderItem> itemQueryWrapper = new LambdaUpdateWrapper<>();
        itemQueryWrapper.in(OrderItem::getId, itemList)
                .set(OrderItem::getRefundStatusCode, OrderItemConst.RefundStatusEnum.REFUNDING.getCode());
        itemService.update(itemQueryWrapper);
        return true;
    }

    @Override
    public boolean cancelRefundById(Long id) {
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getId, id)
                .set(Order::getRefundStatusCode, OrderRefundConst.StatusEnum.CANCEL.getCode());
        return this.getService().update(updateWrapper);
    }
}
